(function($) {
  $.fn.mediaPicker = function(opts) {
		  
	return this.each(function() {
  		 
		var $this = $(this);
        
        
		$this.fancybox({
			'width'				: '980px',
			'height'			: '90%',
			'autoScale'			: true,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'type'				: 'ajax',
            'href'              : opts.href,
			'onComplete'		:	function(button) {
			     	opts.button = button;
					$.fn.mediaPicker.libLoaded(opts);
				}
								   
		});
//		
		$.fn.mediaPicker.libLoaded = function (opts){
			
            if(opts.multiple){
				// Multiple Pic Mode
				// Remove content from paginator

				// Picture Click
				$('#filelist li').live('click',function(){
				    
					li = this;
					if(!li.getAttribute('added'))
					{
						$.fn.mediaPicker.getMedia(opts,li.getAttribute('media_id'),li.getAttribute('media_file'),li.getAttribute('media_screen'),li.getAttribute('media_type'),li.getAttribute('media_extension'),li.getAttribute('media_title'),li.getAttribute('youtube_id'),li.getAttribute('cont_ids'));
						li.getAttribute('added','true')
						$(li).fadeTo('fast', 0.1);
					}
					//$('#filelist li').die('click');					
				});
				
			}else{
			
			     
				// One Pic Mode
                
                $('#filelist li').live('click',function(){
				    
                    
                      
					var li = $(this);
                    
                    $.fn.mediaPicker.getMedia(opts,this.getAttribute('media_id'),this.getAttribute('media_file'),this.getAttribute('media_screen'),this.getAttribute('media_type'),this.getAttribute('media_extension'),this.getAttribute('media_title'),this.getAttribute('youtube_id'),this.getAttribute('cont_ids'));
					$('#filelist li').die('click');
					$.fancybox.close();			
				});
			}

			


			/*
			$('.fancyAdd').click(function(){
				console.info($.fancybox);
				$.fancybox.close();	
				$.fancybox({
						'width'				: '75%',
						'height'			: '90%',
						'autoScale'			: false,
						'transitionIn'		: 'none',
						'transitionOut'		: 'none',
						'type'				: 'iframe',
						'href'				: '/admin/medialib/add'
		
					});
			})
			*/
		};
		

		
		//$this.attr('href',opts.href);
		
		
		
		// One File Mode
		$.fn.mediaPicker.getMedia = function(opts,media_id,media_file,media_screen,media_type,media_extension,media_title,youtube_id,cont_ids)
		{

			var ret = {
						'media_file':media_file,
						'media_screen':media_screen,
						'media_id':media_id,
						'media_type':media_type,
						'media_extension':media_extension,
						'media_title':media_title,
						'youtube_id':youtube_id,
						'cont_ids':cont_ids,
						'button':opts.button
					  }
			opts.onInsert(ret);
		}
		
		
	});
	
  }
})(jQuery);
